/**
 * @author 0283000106
 * @date 2020年2月23日-下午2:32:37
 */
package com.zte.claa.inficombo.csa.app.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFCmdBuilder;
import com.zte.claa.inficombo.csa.app.controller.ret.AicPhotoQryAck;
import com.zte.claa.inficombo.csa.app.dao.mysql.impl.CameraPhotoDataMapper;
import com.zte.claa.inficombo.csa.app.model.dev.DevBase;
import com.zte.claa.inficombo.csa.app.model.dev.DevTypeModel;
import com.zte.claa.inficombo.csa.app.model.redis.DevMeteData;
import com.zte.claa.inficombo.csa.app.service.photo.bean.CameraPhotoData;
import com.zte.claa.inficombo.csa.app.service.rptparse.ParserContainer;
import com.zte.claa.inficombo.csa.app.util.JsonUtils;

import io.swagger.annotations.ApiOperation;

/**
 * @author 0283000106
 * 
 * 该controller仅用于接收AIC的图像数据获取请求.
 *
 */

@RestController
@RequestMapping("/inficombo/mih/")
public class MihApiController extends BaseController {	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private static final String AIC_ACCESS_TOKEN = "Claa2017";
	// logger
	private Logger logger = LoggerFactory.getLogger(MihApiController.class);
	
	@Autowired
	private CameraPhotoDataMapper photoDataMapper;
	
	@Autowired
	private ParserContainer parserContainer;
	
	
	/**
	 * AIC查询CSA中保存的图像数据
	 *  
	 * ctx+'/inficombo/mih/meterdata';	
	   var ajaxPara = {deveui:deveui,reporttime:reporttime,value:value,photourl:photourl}; 
	 */
	@ApiOperation(value = "蜜獾表计数据项信息", notes = "")
	@RequestMapping(value={"/meterdata"}, method = RequestMethod.POST)
	@ResponseBody	
	public String receiveMihMeterData(HttpServletRequest request, HttpServletResponse response) throws Exception{
		logger.info("Receive mih device meterdata info String: " + request);
		String deveui = request.getParameter("deveui"); 
		String collecttime = request.getParameter("time"); 
		String finalReading = request.getParameter("finalReading"); 
		String photourl = request.getParameter("picturePath");
		DevBase devbase = this.parserContainer.getCacheManager().getDev(deveui);
        if(null == devbase){
        	logger.error("ReceiveMihMeterData, devbase is not existed, deveui:"+deveui);
        	return "error";
        }
        String devTypeId = devbase.getDevType();
		DevTypeModel dtm = this.parserContainer.getCacheManager().getDevTypeModel(devTypeId);
		if(dtm == null || dtm.getDmList() == null){
			logger.error("ReceiveMihMeterData, Can not get datamodel for devtype="+devTypeId);
			return "error";
		}
		DevMeteData meteData = new DevMeteData();
		if(null!=collecttime && !"".equals(collecttime)){
			meteData.setRpttime(new Timestamp(sdf.parse(collecttime).getTime()));
		}
		Map<String, Object> mdata = new HashMap<String, Object>();
		String photoid = ""+Math.abs(UUID.randomUUID().getLeastSignificantBits());
		mdata.put("finalreading", finalReading);
		mdata.put("photoid", photoid);	
		meteData.setAppeui(devbase.getAppEui());
		meteData.setDeveui(devbase.getDevEui());
		meteData.setDevname(devbase.getDevName());
		meteData.setDevtype(devTypeId);
		meteData.setPort("0");
		meteData.setProjectid(devbase.getProjectId());
		meteData.setMdata(mdata);
		// 持久化数据.
		this.parserContainer.getPersisService().saveDevMeteData(meteData, dtm.getBase().getTbname());		
        // 将图片数据存入数据库
        CameraPhotoData camPhotoData = new CameraPhotoData();
        camPhotoData.setDeveui(devbase.getDevEui());
        camPhotoData.setPhotoid(photoid);
        camPhotoData.setPhototype(1); //后缀名*.jpg
        camPhotoData.setProjectid(devbase.getProjectId());
        downloadAndSavePicture(camPhotoData,photourl);	
		// 5.构造广播数据，进行redis发布...
		String pubMsg = JsonUtils.toJson(meteData);
		this.parserContainer.getUpdataPublisher().publishMessage(pubMsg);
		logger.info("[*^_^*]Publish metedata message ok: "+pubMsg);		
		return "ok";
	}	
	
	//链接url下载图片
    private void downloadAndSavePicture(CameraPhotoData camPhotoData, String urlList) throws Exception {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }           
            // 插入图片数据
            camPhotoData.setPhoto(output.toByteArray());
            photoDataMapper.addCameraPhotoData(camPhotoData);
            dataInputStream.close();
            logger.info("[*^_^*]Save picture data ok,deveui:"+camPhotoData.getDeveui()+",url:"+urlList);	
        } catch (MalformedURLException e) {
        	logger.info("Save picture data error,msg:"+e.getMessage());	
        } catch (IOException e) {
        	logger.info("Save picture data error,msg:"+e.getMessage());
        }
    }
}
